package com.chenjj.bankm.example.consumer.ctrl;

import com.chenjj.bankm.example.consumer.service.ProviderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
public class SimpleRestController {

    @Autowired
    ProviderService providerService;

    /**
     * Rest服务端使用Feign发起http请求,然后得到数据返回给前端----gotoUser是为了和provider的getUser区分开来
     * @param id
     * @return
     */
    @GetMapping(value = "/gotoUser")
    @HystrixCommand(fallbackMethod = "gotoUserFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    @ResponseBody
    public Map<String,Object> gotoUser(@RequestParam Integer id) throws InterruptedException {

        //模拟熔断
        Thread.sleep(new Random().nextInt(5000));
        System.out.println("gotoUser executed!");
        Map<String,Object> data = providerService.getUser(id);
        return data;
    }

    public Map<String,Object> gotoUserFallback( Integer id)  {
        Map<String,Object> data = new HashMap<>();
        System.out.println("gotoUserFallback executed!");
        data.put("info","gotoUserFallback executed!");
        return data;
    }
}
